package classconverstation.cscl.ist.psu.edu.client.services;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import classconverstation.cscl.ist.psu.edu.server.DBConnector;
import classconverstation.cscl.ist.psu.edu.server.UserChecker;

public class ForumService extends javax.servlet.http.HttpServlet {
    private String DIRECTORY = "/Volumes/Data/Groups/ucs/workspace/WS_DATA_INVEST/uploads/";
    private static final long serialVersionUID = 309579782731258702L;
    private ServletContext context;

    public void init(ServletConfig config) throws ServletException {
        context = config.getServletContext();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String op = request.getParameter("op");
        PrintWriter writer = null;
        
        if (op.equalsIgnoreCase("ga")){ //Get attachment of an object
            String attachment_id = request.getParameter("fid");
            String operator = request.getParameter("operator");
            String file_path = null;
            try {
                file_path = getFilePath(attachment_id);
                if (file_path == null || file_path.length() < 1) {
                    response.setContentType("text/plain");
                    response.setHeader("Cache-Control", "no-cache");
//                    response.setHeader(, );
                    writer = response.getWriter();
                    writer.write("No attachment found");
                    writer.close();
                    return;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
            
            
            File file = new File(file_path);
            
            if (!file.isFile()) {
                response.setContentType("text/plain");
                response.setHeader("Cache-Control", "no-cache");
                writer = response.getWriter();
                writer.write("Invalid file!");
                writer.close();
                return;
            }
            
            RandomAccessFile raf = new RandomAccessFile(file_path, "r");
            
            MimetypesFileTypeMap ftm =  new MimetypesFileTypeMap(file_path);
            String file_type = ftm.getContentType(file_path);
            
            
            String name = file.toString();
            String ext = name.substring(name.lastIndexOf(".")+1, name.length());

            if (ext.equalsIgnoreCase("pdf")) {
                response.setContentType("application/pdf");
            }
            else {
                if (ext.equalsIgnoreCase("doc")) {
                    response.setContentType("application/msword");
                }
                else {
                    response.setContentType(new MimetypesFileTypeMap().getContentType(file));
                }
            }
            
            if (operator.equalsIgnoreCase("dl")) { // asking user if the attachment needs to be downloaded
                response.setHeader("Content-disposition","attachment; filename=\"" + file.getName() + "\"");
            }
            else {
                response.setHeader("Content-disposition","inline; filename=\"" + file.getName() + "\"");
            }
            ServletOutputStream out = response.getOutputStream();
            byte [] loader = new byte [ (int) raf.length() ];
            while ( (raf.read( loader )) > 0 ) {
              out.write( loader );
            }
            out.close();
            raf.close();
            return;
        }
        
        if (op.equalsIgnoreCase("goc")) {
            String order = request.getParameter("o");
            String object_id = request.getParameter("fid");
            String type = request.getParameter("t");
            try {
                StringBuffer sb = getObjAndChildren(object_id, Integer.parseInt(type), order);
                response.setContentType("text/plain");
                response.setHeader("Cache-Control", "no-cache");
                writer = response.getWriter();
                writer.write(sb.toString());
                writer.close();
                return;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if (op.equalsIgnoreCase("ap")) {
            String parent_id = request.getParameter("parentid");
            String content = request.getParameter("cnt");
            String post_type = request.getParameter("itype");
            String uid = request.getParameter("uid");
            String cls_id = request.getParameter("cls");
            try {
                createPost(Integer.parseInt(cls_id), uid, 2, parent_id, content, Integer.parseInt(post_type));
                return;
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if (op.equalsIgnoreCase("ac")) {
        	String parent_id = request.getParameter("parentid");
        	String content = request.getParameter("cnt");
        	String uid = request.getParameter("uid");
        	String cls_id = request.getParameter("cls");
        	try {
                createComment(Integer.parseInt(cls_id), uid, 3, parent_id, content);
                return;
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if (op.equalsIgnoreCase("ce")) {
            String content = request.getParameter("cnt");
            String uid = request.getParameter("uid");
            String cls_id = request.getParameter("cls");
            try {
                createEntry(Integer.parseInt(cls_id), uid, content);
                return;
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if (op.equalsIgnoreCase("gforums")) {
            String cls_id = request.getParameter("cls");  
            String type = request.getParameter("t");            
            String order = request.getParameter("o");
            try {
                StringBuffer sb = getForums(Integer.parseInt(cls_id), Integer.parseInt(type), order);
                response.setContentType("text/plain");
                response.setHeader("Cache-Control", "no-cache");
                writer = response.getWriter();
                writer.write(sb.toString());
                writer.close();
                return;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if (op.equalsIgnoreCase("gds")) {
            String parent_id = request.getParameter("forumid");  
//          String type = request.getParameter("t");            
            String order = request.getParameter("o");
            try {
                StringBuffer sb = getDicussions(parent_id, order);
                response.setContentType("text/plain");
                response.setHeader("Cache-Control", "no-cache");
                writer = response.getWriter();
                writer.write(sb.toString());
                writer.close();
                return;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart) {
            String return_id = null;
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Set factory constraints
            factory.setSizeThreshold(10*1024*1024); // 10 MB
            factory.setRepository(new File(DIRECTORY));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            // Set overall request size constraint
            upload.setSizeMax(10*1024*1024);
            String destinationDir = DIRECTORY;
            // Parse the request
            try {
                List /* FileItem */ items = upload.parseRequest(req);
//              Iterator iterator = items.iterator();
                
//              FileItemIterator iterator = upload.getItemIterator(request);
                Iterator iterator = items.iterator();
                FileItem tmp_item;
                Properties prop = new  Properties();
                while (iterator.hasNext()) {
                    tmp_item = (FileItem) iterator.next();
                    if(tmp_item.isFormField()) {
                        prop.put(tmp_item.getFieldName(), tmp_item.getString());
                    }
                }
                for (int i = 0; i < items.size(); i++) {
                    FileItem item = (FileItem) items.get(i);
                    if(item.isFormField()) {
                    } else {
                            if (item.getName().lastIndexOf('.') > -1) {
                                File file = safeFile(destinationDir,item.getName());
                                item.write(file);
                                return_id = createTopic(Integer.parseInt(prop.getProperty("cls")), prop.getProperty("uid"), Integer.parseInt(prop.getProperty("type")), prop.getProperty("parent_id"), 
                                        prop.getProperty("content"), prop.getProperty("title"), DIRECTORY + file.getName(), Integer.parseInt(prop.getProperty("itype")));
                            }
                            else {
                                return_id = createTopic(Integer.parseInt(prop.getProperty("cls")), prop.getProperty("uid"), Integer.parseInt(prop.getProperty("type")), prop.getProperty("parent_id"), 
                                        prop.getProperty("content"), prop.getProperty("title"), null, Integer.parseInt(prop.getProperty("itype")));
                            }
                        }
                }
                
                PrintWriter writer = resp.getWriter();
                writer.write(return_id);
                writer.close();
                
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        else {
            doGet(req, resp);
        }
    }
    
    private StringBuffer getDicussions(String forum, String order) throws SQLException {
        String sql = "SELECT * FROM " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
        " where parentid = ? and type = ? order by " + order;
        Connection conn = DBConnector.getInstance().getConnection();
        
        PreparedStatement pstat = conn.prepareStatement(sql);
        pstat.setString(1, forum);
        pstat.setInt(2, 1);
        ResultSet rs = pstat.executeQuery();
        StringBuffer sb = null;
        if (rs.first()){
            rs.beforeFirst();
            rs.next();
            sb = new StringBuffer();
            sb.append("[\n");
            
            sb.append("     {\"fid\": \"" + rs.getString("fid") + "\",\n");
            sb.append("            \"cid\": \"" + rs.getString("cid") + "\",\n");
            sb.append("            \"uid\": \"" + rs.getString("uid") + "\",\n");
            sb.append("            \"type\": \"" + rs.getInt("type") + "\",\n");
            sb.append("            \"title\": \"" + rs.getString("title") + "\",\n");
            
            sb.append("            \"content\": \"" + rs.getString("content") + "\",\n");
            sb.append("            \"link\": \"" + rs.getString("link") + "\",\n");
            sb.append("            \"time\": \"" + rs.getTimestamp("time").getTime() + "\",\n");
            sb.append("            \"likes\": \"" + rs.getInt("likes") + "\",\n");
            sb.append("            \"itemType\": \"" + rs.getInt("itemType") + "\",\n");
            sb.append("            \"parentid\": \"" + rs.getString("parentid") + "\"\n");
            sb.append("}"); 
//            sb.deleteCharAt(sb.length() - 1);
            sb.append("\n]");

            rs.close();
            rs = null;
            pstat.close();
            pstat = null;
            conn.close();
            conn = null;
        }
        else {
            rs.close();
            rs = null;
            pstat.close();
            pstat = null;
            conn.close();
            conn = null;
        }
        return sb;
    }
    
    private StringBuffer getForums(int cls, int type, String order) throws SQLException {
        String sql = "SELECT * FROM " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
        " where cid = ? and type = ? order by " + order;
        Connection conn = DBConnector.getInstance().getConnection();
System.out.println(sql);    
        PreparedStatement pstat = conn.prepareStatement(sql);
        pstat.setInt(1, cls);
        pstat.setInt(2, type);
        ResultSet rs = pstat.executeQuery();
        StringBuffer sb = null;
        if (rs.first()){
            rs.beforeFirst();
            sb = new StringBuffer();
            sb.append("[\n");

            while (rs.next()) {
                sb.append("     {\"fid\": \"" + rs.getString("fid") + "\",\n");
                sb.append("            \"cid\": \"" + rs.getString("cid") + "\",\n");
                sb.append("            \"uid\": \"" + rs.getString("uid") + "\",\n");
                sb.append("            \"type\": \"" + rs.getInt("type") + "\",\n");
                sb.append("            \"title\": \"" + rs.getString("title") + "\",\n");
                
                sb.append("            \"content\": \"" + rs.getString("content") + "\",\n");
                sb.append("            \"link\": \"" + rs.getString("link") + "\",\n");
                sb.append("            \"time\": \"" + rs.getTimestamp("time").getTime() + "\",\n");
                sb.append("            \"likes\": \"" + rs.getInt("likes") + "\",\n");
                sb.append("            \"itemType\": \"" + rs.getInt("itemType") + "\",\n");
                sb.append("            \"parentid\": \"" + rs.getString("parentid") + "\"\n");
                sb.append("},"); 
            }
                sb.deleteCharAt(sb.length() - 1);
            sb.append("\n]");

            rs.close();
            rs = null;
            pstat.close();
            pstat = null;
            conn.close();
            conn = null;
        }
        else {
            rs.close();
            rs = null;
            pstat.close();
            pstat = null;
            conn.close();
            conn = null;
        }
        return sb;
    }
    
    private String createTopic(int cls_id, String uid, int type, String parent_id, String content,
            String title, String link, int item_type) throws SQLException {
        String sql = "INSERT INTO " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
            " (fid, cid, uid, type, parentid, content, title, link, likes, itemType, time)" +
            " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        System.out.println(sql);
        
        System.out.println(cls_id + ", " + uid + ", " + type + ", " + parent_id + ", " + content + ", " + title + ", " + 
                link + ", " + item_type);
        
        String fid = UUID.randomUUID().toString();
        
        Connection conn = DBConnector.getInstance().getConnection();
    
        PreparedStatement pstat = conn.prepareStatement(sql);
        pstat.setString(1, fid);
        pstat.setInt(2, cls_id);
        pstat.setString(3, uid);
        pstat.setInt(4, type);
        pstat.setString(5, parent_id);
        pstat.setString(6, content);
        pstat.setString(7, title);
        pstat.setString(8, link);
        pstat.setInt(9, 0);
        pstat.setInt(10, item_type);
        pstat.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
        pstat.execute();
        pstat.close();
        pstat = null;
        
        conn.close();
        conn = null;
        
        return fid;
    }
    
    private StringBuffer getObjAndChildren(String id, int type, String order) throws SQLException {
        StringBuffer sb = null;
        StringBuffer sb1 = null;
        String pure_text;
        Connection conn = DBConnector.getInstance().getConnection();
        String sql = "SELECT * FROM " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
            " where fid = ? order by " + order;
        

        System.out.println(sql);
        
        PreparedStatement pstat = conn.prepareStatement(sql); 
        ResultSet rs;
        pstat.setString(1, id);
//        pstat.setInt(2, type);
        rs = (ResultSet) pstat.executeQuery();
        if (rs.first()){
            System.out.println(sql);
            rs.beforeFirst();
            rs.next();
            sb = new StringBuffer();
            sb.append("[\n");
            
            sb.append("     {\"fid\": \"" + rs.getString("fid") + "\",\n");
            sb.append("            \"cid\": \"" + rs.getString("cid") + "\",\n");
            sb.append("            \"uid\": \"" + rs.getString("uid") + "\",\n");
            sb.append("            \"ufullname\": \"" + UserChecker.getUser(rs.getString("uid")).getFullName() + "\",\n");
            sb.append("            \"type\": \"" + rs.getInt("type") + "\",\n");
            sb.append("            \"title\": \"" + rs.getString("title") + "\",\n");
            
            pure_text = rs.getString("content");
            if (pure_text != null) {
                sb1 = new StringBuffer(pure_text);
                if (sb1.indexOf("\"") > -1) {
                    int index_of = sb1.indexOf("\"");
                    while (index_of > -1) {
                        sb1 = sb1.insert(index_of, '\\');
                        index_of = sb1.indexOf("\"", index_of + 2);
                    }
                }
            }
            else {
                sb1 = new StringBuffer();
            }
            
            sb.append("            \"content\": \"" + sb1.toString() + "\",\n");
            sb.append("            \"link\": \"" + rs.getString("link") + "\",\n");
            sb.append("            \"time\": \"" + rs.getTimestamp("time").getTime() + "\",\n");
            sb.append("            \"likes\": \"" + rs.getInt("likes") + "\",\n");
            sb.append("            \"itemType\": \"" + rs.getInt("itemType") + "\",\n");
            sb.append("            \"parentid\": \"" + rs.getString("parentid") + "\",\n");
            

            rs.close();
            rs = null;
            pstat.close();
            pstat = null;
            
            
            sql = "SELECT * FROM " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
                " where parentid = ? and type = ? order by " + order;;
            pstat = conn.prepareStatement(sql);
            pstat.setString(1, id);
            pstat.setInt(2, type);
            rs = pstat.executeQuery();
            if (rs.first()) {
                System.out.println(sql);
                sb.append("         \"items\": [ \n");
                rs.beforeFirst();
                while (rs.next()) {
                    sb.append("            {\"fid\": \"" + rs.getString("fid") + "\",\n");
                    sb.append("            \"cid\": \"" + rs.getString("cid") + "\",\n");
                    sb.append("            \"uid\": \"" + rs.getString("uid") + "\",\n");
                    sb.append("            \"ufullname\": \"" + UserChecker.getUser(rs.getString("uid")).getFullName() + "\",\n");
                    sb.append("            \"type\": \"" + rs.getInt("type") + "\",\n");
                    sb.append("            \"title\": \"" + rs.getString("title") + "\",\n");
                    
                    pure_text = rs.getString("content");
                    if (pure_text != null) {
                        sb1 = new StringBuffer(pure_text);
                        if (sb1.indexOf("\"") > -1) {
                            int index_of = sb1.indexOf("\"");
                            while (index_of > -1) {
                                sb1 = sb1.insert(index_of, '\\');
                                index_of = sb1.indexOf("\"", index_of + 2);
                            }
                        }
                    }
                    else {
                        sb1 = new StringBuffer();
                    }
                    
                    sb.append("            \"content\": \"" + sb1.toString() + "\",\n");
                    sb.append("            \"link\": \"" + rs.getString("link") + "\",\n");
                    sb.append("            \"time\": \"" + rs.getTimestamp("time").getTime() + "\",\n");
                    sb.append("            \"likes\": \"" + rs.getInt("likes") + "\",\n");
                    sb.append("            \"itemType\": \"" + rs.getInt("itemType") + "\",\n");
                    sb.append("            \"parentid\": \"" + rs.getString("parentid") + "\"\n");
                    sb.append("           },\n");
                }
                sb.deleteCharAt(sb.length() - 1);
                sb.deleteCharAt(sb.length() - 1);
                sb.append("]\n");
            }
//            sb.deleteCharAt(sb.length() - 1);
//            sb.deleteCharAt(sb.length() - 1);
            sb.append("},"); 
//            sb.deleteCharAt(sb.length() - 1);

            sb.deleteCharAt(sb.length() - 1);
            sb.append("\n]");
            
            rs.close();
            rs = null;
            pstat.close();
            pstat = null;
            conn.close();
            conn = null;
        }
        else {
             rs.close();
             rs = null;
             pstat.close();
             pstat = null;
             conn.close();
             conn = null;
        }
        return sb;
    }
    
    private String getFilePath(String id) throws SQLException {
        Connection conn = DBConnector.getInstance().getConnection();
        String sql = "SELECT link FROM " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
            " where fid = ?";
        PreparedStatement pstat = conn.prepareStatement(sql); 
        ResultSet rs;
        pstat.setString(1, id);
        String path = null;
        rs = (ResultSet) pstat.executeQuery();
        if (rs.first()){
            rs.beforeFirst();
            rs.next();
            path = rs.getString(1);
            rs.close();
            rs = null;
            pstat.close();
            pstat = null;
            conn.close();
            conn = null;
        }
        else {
             rs.close();
             rs = null;
             pstat.close();
             pstat = null;
             conn.close();
             conn = null;
        }
        return path;
    }
    
    private String createPost(int cls_id, String uid, int type, String parent_id, String content,
            int item_type) throws SQLException {
        String sql = "INSERT INTO " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
            " (fid, cid, uid, type, parentid, content, title, link, likes, itemType, time)" +
            " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        String fid = UUID.randomUUID().toString();
        
        Connection conn = DBConnector.getInstance().getConnection();
    
        PreparedStatement pstat = conn.prepareStatement(sql);
        pstat.setString(1, fid);
        pstat.setInt(2, cls_id);
        pstat.setString(3, uid);
        pstat.setInt(4, type);
        pstat.setString(5, parent_id);
        pstat.setString(6, content);
        pstat.setString(7, "a post");
        pstat.setString(8, null);
        pstat.setInt(9, 0);
        pstat.setInt(10, item_type);
        pstat.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
        pstat.execute();
        pstat.close();
        pstat = null;
        
        conn.close();
        conn = null;
        
        return fid;
    }

    private String createComment(int cls_id, String uid, int type, String parent_id, String content) throws SQLException {
        String sql = "INSERT INTO " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
            " (fid, cid, uid, type, parentid, content, title, link, likes, itemType, time)" +
            " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        String fid = UUID.randomUUID().toString();
        
        Connection conn = DBConnector.getInstance().getConnection();
    
        PreparedStatement pstat = conn.prepareStatement(sql);
        pstat.setString(1, fid);
        pstat.setInt(2, cls_id);
        pstat.setString(3, uid);
        pstat.setInt(4, type);
        pstat.setString(5, parent_id);
        pstat.setString(6, content);
        pstat.setString(7, "a comment");
        pstat.setString(8, null);
        pstat.setInt(9, 0);
        pstat.setInt(10, 0);
        pstat.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
        pstat.execute();
        pstat.close();
        pstat = null;
        
        sql = "UPDATE " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
        		" SET likes = likes + 1 where fid = ? ";
        
        pstat = conn.prepareStatement(sql);
        pstat.setString(1, parent_id);
        pstat.execute();
        
        pstat.close();
        pstat = null;
        
        conn.close();
        conn = null;
        
        return fid;
    }

    private String createEntry(int cls_id, String uid, String content) throws SQLException {
        String sql = "INSERT INTO " + ClassConversationUtil.ClassConversationDB + "." + ClassConversationUtil.ClassConversationForumTable + 
            " (fid, cid, uid, type, parentid, content, title, link, likes, itemType, time)" +
            " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        String fid = UUID.randomUUID().toString();
        
        Connection conn = DBConnector.getInstance().getConnection();
    
        PreparedStatement pstat = conn.prepareStatement(sql);
        pstat.setString(1, fid);
        pstat.setInt(2, cls_id);
        pstat.setString(3, uid);
        pstat.setInt(4, 0);
        pstat.setString(5, Integer.toString(cls_id));
        pstat.setString(6, content);
        pstat.setString(7, "a folder");
        pstat.setString(8, null);
        pstat.setInt(9, 0);
        pstat.setInt(10, 0);
        pstat.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
        pstat.execute();
        pstat.close();
        pstat = null;
        
        conn.close();
        conn = null;
        
        return fid;
    }
    
    private File safeFile(String path, String name) {
        File file = new File(path, name);
        if (file.exists()) {
            String file_name = name.substring(0, name.lastIndexOf('.'));
            String file_extension = name.substring(name.lastIndexOf(".")+1, name.length());
            return new File(path, file_name + "_" + System.currentTimeMillis() + "." + file_extension);
        }
        else {
            return file;
        }
    }
}